package com.onlygx.dva.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 版权所有 泰山信息技术有限公司
 *
 * @Author: yuhaitao
 * @Date 2021/3/26 下午7:20
 */
@Service
@RequiredArgsConstructor
public class JsonUtil {

    final ObjectMapper objectMapper;

    public <T> List<T> parseList(String str, Class<T> t) {
        try {
            CollectionType listType = objectMapper.getTypeFactory().constructCollectionType(List.class, t);
            return objectMapper.readValue(str, listType);
        }catch (JsonProcessingException e){
            throw new NullPointerException("JSON 解析失败：" + e.getMessage());
        }
    }

    public <T> T parseObj(String str, Class<T> t) {
        try {
            return objectMapper.readValue(str, t);
        }catch (JsonProcessingException e){
            throw new NullPointerException("JSON 解析失败：" + e.getMessage());
        }
    }

    public String toJSONString(Object obj){
        try {
            return objectMapper.writeValueAsString(obj);
        }catch (JsonProcessingException e){
            throw new NullPointerException("JSON 转换失败：" + e.getMessage());
        }
    }

    public <T> T parseVPJSON(String str, Class<T> t){
        R r = parseObj(str, R.class);
        if (r.code == 0){
            return parseObj(toJSONString(r.data), t);
        }else {
            return null;
        }
    }

    public static class R {
        private int code;
        private Object data;
        private String msg;

        public int getCode() {
            return code;
        }

        public void setCode(int code) {
            this.code = code;
        }

        public Object getData() {
            return data;
        }

        public void setData(Object data) {
            this.data = data;
        }

        public String getMsg() {
            return msg;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }
    }


    public <T> T parseRTJSON(String str, Class<T> t){
        RT r = parseObj(str, RT.class);
        if (r.code == 200){
            return parseObj(toJSONString(r.data), t);
        }else {
            return null;
        }
    }


    public static class RT {
        private int code;
        private Object data;
        private String message;

        public int getCode() {
            return code;
        }

        public void setCode(int code) {
            this.code = code;
        }

        public Object getData() {
            return data;
        }

        public void setData(Object data) {
            this.data = data;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String msg) {
            this.message = msg;
        }
    }
}
